package own.stu.jobgib.playown.tools.metrix;

import com.codahale.metrics.*;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MetrixTest {

    public static void main(String[] args) {

        HelService helService = new HelService();
        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            service.submit(() -> {
                for (int j = 0; j < 40; j++) {
                    helService.handleRequest("oijf");
                    try {
                        TimeUnit.MILLISECONDS.sleep(200);
                    } catch (InterruptedException e) {
                    }
                }
            });
        }

        helService.waitSeconds(10);
        service.shutdown();
    }

    public static class HelService {

        static final MetricRegistry metricRegistry = new MetricRegistry();
        Meter requests = metricRegistry.meter("request");
        Counter counter = metricRegistry.counter("counter");
        Histogram histogram;
        Timer timer;
        Gauge gauge;
        ThreadLocal<Integer> threadLocal;

        {
            histogram = metricRegistry.histogram("histogram");
            threadLocal = ThreadLocal.withInitial(() -> new Random().nextInt(10));
            timer = metricRegistry.timer("timer");
//            gauge = metricRegistry.gauge("gauge");
        }


        public HelService() {
            startReport();
        }

        public void handleRequest(Object request) {
            requests.mark();
            counter.inc();
            histogram.update(threadLocal.get());
            timer.update(10, TimeUnit.MILLISECONDS);
            gauge.getValue();
        }

        public void startReport() {
            ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(metricRegistry)
                    .convertRatesTo(TimeUnit.SECONDS)
                    .convertDurationsTo(TimeUnit.MILLISECONDS)
                    .build();

            consoleReporter.start(1, TimeUnit.SECONDS);
        }

        public void waitSeconds(int sec) {
            try {
                Thread.sleep(sec * 1000);
            } catch (InterruptedException e) {
            }
        }
    }
}
